package com.lagou.rpc.consumer.config;

import com.lagou.rpc.consumer.client.RpcClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
@Component
public class Watcher {
    public void watchZookeeperNode(CuratorFramework client, String path) throws Exception {


        TreeCache treeCache = new TreeCache(client, path);


        TreeCacheListener listener = new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData data = event.getData();
                if(data == null ){return;}
                String str = data.getPath().substring(data.getPath().lastIndexOf("/") + 1);
                TreeCacheEvent.Type type = event.getType();
                if (type == TreeCacheEvent.Type.NODE_ADDED) {
                    String[] split = str.split(":");
                    if (split.length != 2) {
                        return;
                    }
                    System.out.println("监听到有节点加入" + str);
                    if (!value.RpcMap.containsKey(str)) {
                        RpcClient rpcClient = new RpcClient(split[0], Integer.valueOf(split[1]));
                        value.RpcMap.put(str, rpcClient);
                    }
                } else if (type == TreeCacheEvent.Type.NODE_REMOVED) {
                    //删除节点
                    System.out.println("监听到有节点删除" + str);
                    value.RpcMap.remove(str);
                }


                System.out.println("现有的链接");
                Iterator<Map.Entry<String, RpcClient>> iterator = value.RpcMap.entrySet().iterator();
                if (iterator.hasNext()) {
                    Map.Entry<String, RpcClient> next = iterator.next();
                    String key = next.getKey();
                    RpcClient value = next.getValue();
                    System.out.println(key + ":" + value);
                }


            }
        };
        treeCache.getListenable().addListener(listener);
        treeCache.start();
    }


}
